package cn.intotw.rdcj.task.spiders.netty;


import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Created by Chenxiang
 *
 * @generator: IntelliJ IDEA
 * @description:
 * @project: rdcj
 * @package: cn.intotw.rdcj.commodity.spiders.netty
 * @date: 2020年07月23日 14时52分
 */
@Slf4j
public class SpidersClientInboundHandler extends MessageToMessageDecoder<FullHttpResponse> {
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        log.error("{}异常", this.getClass().getName(), throwable);

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpResponse fullHttpResponse, List<Object> list) throws Exception {
        HttpResponseStatus status = fullHttpResponse.status();
        log.info("Http status: " + status);
        //Http OK
        if(status.code()==200){
            //log headers
            if (!fullHttpResponse.headers().isEmpty()) {
                for (CharSequence name: fullHttpResponse.headers().names()) {
                    for (CharSequence value: fullHttpResponse.headers().getAll(name)) {
                        log.info("HEADER: " + name + " = " + value);
                    }
                }
            }
            String httpBody = fullHttpResponse.content().toString(StandardCharsets.UTF_8);
            list.add(httpBody);
        }
    }
}
